Android Studio
Télécharger directement depuis le site d'Android développeur Android Studio
Si vous avez besoin de plus d'information pour d'autre Système d'exploitation Guide Installation
Télécharger directement depuis le site d'Android développeur Android Studio
Si vous avez besoin de plus d'information pour d'autre Système d'exploitation Guide Installation
Pour pouvoir tester l'application, on va devoir installer un émulateur. Dans Android Studio il y a déjà une solution de présente pour cela
Lors de la création d'une application Android, il est important de toujours tester votre application sur un appareil réel avant de la diffuser aux utilisateurs. Pour pouvoir déployer votre application sur un téléphone vous allez devoir suivre plusieurs étapes. DOC
Android évolue vite, il faut constamment aller voir sur la documentation officiel les changements. Documentation Officiel
La documentation est subdivisée en plusieurs parties :

Une fonctionnalité intéressante lors d'une présentation est de pouvoir faire le miroir du téléphone et l'afficher sur un écran. Voici deux applications qui le font:
Android est un système open source basé sur un noyau Linux créer pour un large éventail d'appareils

La base de la plate-forme Android est le noyau Linux. Par exemple, Android Runtime (ART) s'appuie sur le noyau Linux pour les fonctionnalités sous-jacentes telles que le threading et la gestion de la mémoire de bas niveau.
L'utilisation d'un noyau Linux permet à Android de tirer parti des principales fonctionnalités de sécurité et permet aux fabricants d'appareils de développer des pilotes matériels pour un noyau bien connu.
La couche d'abstraction matérielle (HAL) fournit des interfaces standard qui exposent les capacités matérielles de l'appareil au cadre d'API Java de niveau supérieur. Le HAL se compose de plusieurs modules de bibliothèque, chacun implémentant une interface pour un type spécifique de composant matériel, tel que la caméra ou le module Bluetooth. Lorsqu'une API d'infrastructure effectue un appel pour accéder au matériel de l'appareil, le système Android charge le module de bibliothèque pour ce composant matériel.
Pour les appareils exécutant Android version 5.0 (niveau API 21) ou supérieur, chaque application s'exécute dans son propre processus et avec sa propre instance d'Android Runtime (ART). ART est écrit pour exécuter plusieurs machines virtuelles sur des appareils à faible mémoire en exécutant des fichiers DEX, un format de bytecode conçu spécialement pour Android et optimisé pour une empreinte mémoire minimale. Anciennement on utilisait la DVM ou Dalvik Virtual Machine pour gérer les applications.
De nombreux composants et services principaux du système Android sont construits à partir des bibliothèques natives écrites en C et C++. La plate-forme Android fournit des API de framework Java pour exposer les fonctionnalités de certaines de ces bibliothèques natives aux applications.
Si vous développez une application qui nécessite du code C ou C++, vous pouvez utiliser le NDK Android pour accéder à certaines de ces bibliothèques de plate-forme natives directement à partir de votre code natif.
L'ensemble des fonctionnalités du système d'exploitation Android est à votre disposition via des API écrites en langage Java. Ces API constituent les blocs de construction dont vous avez besoin pour créer des applications Android en simplifiant la réutilisation des composants et services système modulaires de base,.
Android est livré avec un ensemble d'applications de base pour la messagerie électronique, la messagerie SMS, les calendriers, la navigation sur Internet, les contacts, etc. Les applications incluses avec la plate-forme n'ont aucun statut particulier parmi les applications que l'utilisateur choisit d'installer. Ainsi, une application tierce peut devenir le navigateur Web par défaut de l'utilisateur.
Même si les téléphone deviennent de plus en plus puissant, ne pas oublier qu'ils sont beaucoup moins puissants qu'un ordinateur. Une phase d'optimisation de l'application pourrait s'avérer nécessaire.
Google pas créateur d'Android !!
Origine Android est Android Incorporated racheté par Google en 2005
2007 l'Open Handset Alliance 35 entreprises évoluant dans l'univers du mobile avec un OS OpenSource
Les applications Android peuvent être écrites à l'aide des langages Kotlin, Java et C++. Les outils Android SDK compilent votre code avec tous les fichiers de données et de ressources dans un APK ou un Android App Bundle.
Dans le cadre du cours, on utilisera Java pour éviter d'avoir à apprendre un nouveau langage.
Dans la documentation Google veut pousser l'utilisation de Kotlin
ART ou Android Runtime anciennement DVM ou Dalvik Virtual Machine
Création de la première application avec Android Studio et déploiement dans l'émulateur ou le téléphone
Une application android est composée de trois parties
MyApplication
├── app
│ ├── libs
│ └── src
│ ├── androidTest
│ ├── main
│ │ ├── java <--
│ │ ├── res <--
│ │ └── AndroidManifest.xml <--
│ └── test
├── build.gradle <--
└── gradlew
Il existe 4 types de composants possibles dans une application Android :
On peut aussi parler d'un 5ᵉ objet Intent DOC qui sert à faire la liaison entre les 3 premiers. Dans la doc, on le qualifie de messager asynchrone.
Une activité est le point d'entrée pour interagir avec l'utilisateur. Il représente un écran unique avec une interface utilisateur.
En tant que telle, une application différente peut démarrer l'une de ces activités si l'application de messagerie le permet. Par exemple, une application d'appareil photo peut démarrer l'activité dans l'application de messagerie qui compose un nouveau courrier pour permettre à l'utilisateur de partager une image.
Une activité facilite les interactions clés suivantes entre le système et l'application.
On reviendra en détail sur ce composant dans la suite du cours.
Un service est un point d'entrée à usage général pour maintenir une application en arrière-plan un peu comme un thread.
Il s'agit d'un composant qui s'exécute en arrière-plan pour effectuer des opérations de longue durée ou pour effectuer des tâches pour des processus distants. Un service ne fournit pas d'interface utilisateur.
Peut être démarré par une Activity et continuer de s'exécuter en arrière plan
Il existe deux types de services qui indiquent au système comment gérer une application:
Si on a le temps, on traitera les services dans le cours, mais pas évaluer dans le cours.
Composant qui permet au système de transmettre des événements à l'application en dehors d'un flux d'utilisateurs régulier
Permet à l'application de répondre aux annonces de diffusion à l'échelle du système
Pour gérer un ensemble de données dans le système de fichiers, dans une base de données SQLite, sur le Web ou sur tout autre emplacement de stockage persistant auquel votre application peut accéder.
Pour le système, content provider est un point d'entrée dans une application pour accéder à des données nommées, identifiés par un schéma d'URI.
Dans ce répertoire se trouve les ressources que vous allez utiliser dans votre application.
Les ressources sont regroupées par type dans un sous répertoire correspondant :
Répertorie ressource commun :
main
├── java
└── res
├── drawable
├── layout
├── mipmap
└── values
Vous pouvez avoir la liste de tous les sous type ICI mais pour le moment on va décrire les plus communes.
Dans le répertoire res/value on pourra avoir :
On peut faire plusieurs fichiers pour séparer les ressources et s'y retrouver plus facilement.
Il en existe d'autres sous types, mais on les verra au fur et à mesure des besoins.
On reviendra plus tard su comment accéder et utiliser les ressources.
Le système de build Android compile les ressources et le code source de l'application et les regroupe dans des APK(Application PacKage) ou des bundles d'applications Android(AAB) que vous pouvez tester, déployer, signer et distribuer.
Android Studio utilise Gradle, pour automatiser et gérer le processus de construction tout en vous permettant de définir des configurations de construction flexibles et personnalisées.
Chaque projet d'application doit avoir un fichier AndroidManifest.xml (portant précisément ce nom) à la racine de l'ensemble source du projet. Le fichier manifeste décrit les informations essentielles sur votre application pour les outils de génération Android, le système d'exploitation Android et Google Play. On va avoir dans ce fichier:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
On va retrouver dans ce fichier :
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
Informations Importantes :
Lorsque l'on veut modifier ces valeurs, on peut le faire manuellement, mais il est conseillé de passer par l'interface graphique d'Android Studio. Pour y accéder il suffit d'aller dans File

Cette documentation a été mise à jour en janvier 2023. Lors de la création d'un projet android nous propose de l'aide pour choisir la version cible.

Ici on peut voir la liste des versions et des API correspondante. On voit aussi le pourcentage de téléphone que l'on va toucher si on choisit une version.
Par exemple La version 7.1 Nougat avec l'API 25 va toucher 90% des téléphones. Dans ce cas, on pourrait se dire je vais utiliser l'API 17 qui va toucher 99.9% des téléphones. Pas forcément un bon calcul. Si dans votre application vous avez besoin d'utiliser l'empreinte digitale ce ne sera pas possible, car c'est seulement dans l'API 23 que cette fonctionnalité apparait.
En gros, plus on utilise des fonctionnalités récentes moins on va toucher de téléphone, car il faut attendre que les gens mettent à jour le téléphone. Or sous Android ce n'est pas toujours possible. Le système va mettre à jour le téléphone que si celui-ci est capable de le supporter au niveau hardware.
Au moment de concevoir votre application il faudra se poser la question. Quel type de population je veux toucher ? Quelles fonctionnalités j'ai absolument besoin d'avoir?
La fenêtre Logcat d'Android Studio affiche les messages système et les messages que vous avez ajoutés à votre application avec la classe Log. Il affiche les messages en temps réel et conserve un historique afin que vous puissiez voir les messages plus anciens.
Très utile pour déboguer une application :

On peut aussi filtrer les logs en fonction du label ou de la priorité du log.
La classe
Le premier String est le label unique du message. On l'utilisera dans le logcat pour retrouver rapidement notre message
Le deuxième String est le message que l'on veut faire apparaître
Bien faire attention la méthode attend un STRING et pas un autre type. À vous de faire la conversion de type s'il y a besoin.
Il existe aussi un 😄 Log.wtf(String, String) 😄 pour "What a Terrible Failure" ou Quel terrible échec. À utiliser qu'en cas d'erreur incompréhensible.
Faire attention que le Logcat ait bien le focus sur le bon téléphone et ensuite le bon projet. Quand on a plusieurs téléphones ainsi que des émulateurs en même temps on peut vite se faire avoir.
La classe Activity est un composant de base d'une application Android. Comprendre la façon dont les activités sont lancées et assemblées est aussi élément fondamental pour la construction des applications mobiles. Contrairement aux paradigmes de programmation dans lesquels les applications sont lancées avec une méthode main(), c'est le système Android initie le code dans une instance Activity en appelant des méthodes de rappel spécifiques qui correspondent à des étapes spécifiques de son cycle de vie.
La classe Activity fournit un certain nombre de methode callback qui permettent à l'activité de savoir qu'un état a changé : quand le système crée, arrête ou reprend une activité, ou détruit le processus dans lequel l'activité réside.
C'est ce qui permet de contrôler l'activité sans avoir la main sur l'instance de l'objet.

Logique de démarrage d'application de base qui ne doit se produire qu'une seule fois pendant toute la durée de vie de l'activité. Par exemple :
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Juste avant que l'activité soit visible.
Appelée juste après onCreate ou lorsque l'activité a été stoppé
méthode qui doit être rapide
Il s'agit de l'état dans lequel l'application interagit avec l'utilisateur et reste dans cet état jusqu'à la perte du focus.
Appelé après onStart ou lorsque l'activité a été onPause
Appelé car l'activité va être quitté.
C'est ici qu'on doit arrêter toutes les taches qui n'ont pas lieux d'être alors que l'activité n'est plus en premier plan (peut être encore visible dans le cas du multiscreen).
Activité n'est plus visible
Se produit quand une nouvelle activité est lancée et qu'elle couvre tout l'écran ou quand on va simplement quitter l'application.
Effectuer des opérations d'arrêt relativement gourmandes en CPU. Par exemple, pour enregistrer des informations dans une base de données.
même si l'activité est stoppée, elle reste en mémoire.
Si l'activité revient au premier plan on aura onRestart() qui sera appelé.
Activité est complétement détruite car :
Toujours le meilleur moyen de comprendre, c'est souvent de tester.
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
Pour créer une activité, il y a au moins deux étapes à suivre. Généralement on en ajoute une troisième.
public class FirstActivity extends Activity {
}
C'est la classe la plus basique. Dans la pratique, on utilisera AppCompactActivity qui nous permettra d'avoir de la compatibilité avec les anciennes versions d'Android
On va aussi redéfinir la méthode onCreate pour définir la vue. Sinon on aura simplement un écran blanc ce qui n'est pas très utile.
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Le tag intent-filter avec action et category permet d'expliquer que c'est le point d'entrée de l'application
Si on avait une deuxième activité le manifest ressemblerait à
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
android:exported
Généralement on crée un fichier xml dans les resources pour définir la vue de l'activité. On peut toute fois s'en passer et faire une vue sans le XML, tout en code Java.
Le plus simple est de faire new empty activity qui va faire ces trois étapes pour nous.

Une tâche est un ensemble d'activités avec lesquelles les utilisateurs interagissent lorsqu'ils essaient de faire quelque chose dans votre application. Ces activités sont disposées dans une pile - la pile arrière - dans l'ordre dans lequel chaque activité est ouverte.

Lorsque l'activité en cours en démarre une autre, la nouvelle activité est poussée en haut de la pile et prend le focus.
L'activité précédente reste dans la pile est arrêtée, mais conserve l'état de son interface.
Lorsque l'utilisateur effectue l'action de retour ou le programmeur utilise finish(), l'activité en cours est supprimé du haut de la pile (l'activité est détruite) et l'activité précédente reprend (l'état précédent de son interface utilisateur est restauré).
Les activités de la pile ne sont jamais réorganisées, seulement ajouté ou retirées de la pile
Fonctionne comme une structure de donnée dernier entré premier sortie on dit aussi (FILO First In Last Out)
Dans votre application il sera important de bien gérer vos activités pour éviter d'en avoir plusieurs même instance dans la pile

Vous pouvez voir ici comment changer le comportement de la pile. Mais une meilleure analyse adaptée au fonctionnement d'Android est préférable. En général on ne veut pas changer le comportement par défaut.
Interface qui possède les informations globales sur un environnement d'application. Il s'agit d'une classe abstraite que chaque Activité implémente. Il permet d'accéder :
Énormément de classe ont besoin du Context pour fonctionner.
Il existe plusieurs façons de mettre la main dessus
Voici la plus simple et qui permet de le retrouver facilement partout dans la classe.
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
Composant visuel de l'application
Utilise setContentView pour définir la vue
La vue est composée que d'objet de type View ou ViewGroup. Si on fait le parallèle avec votre cours de React JS :

Un chapitre entier sera consacré aux interfaces utilisateurs (UI)
Le layout (mise en page) définit la structure de votre Interface Utilisateur(UI). Tous les éléments du UI sont construits à l'aide de 2 type d'objet :
Au final Le Layout est composé d'un arbre d'objet, comme en javascript avec le DOM (Document Object Model)

Dans la documentation officielle, les View sont appelées communément des "widgets" et les ViewGroup sont appelées des "layouts". Pour éviter de confondre entre "Layout" ViewGroup et "Layout" liste des objets créant la vue, dans ce cours les View seront des composants et les ViewGroup seront des containeurs de la vue et le Layout sera la combinaison de tous les composants et containeurs de la vue.
Si on regarde dans la documentation de référence sur les ViewGroup on peut voir qu'un ViewGroup hérite de View. Au final, on pourrait le voir comme un View possédant une List<View> ou un containeur de View.

Il existe 3 façons de créer des UI :
Dans tous les cas, il faudra définir le Layout dans l'Activity. Pour cela on devra utiliser la méthode setContentView. Il existe plusieurs redéfinitions de cette méthode pour pouvoir affecter le layout à l'Activity en fonction de la façon que l'on veut utiliser.
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
Comme on voit, on définit le Layout dans onCreate. Normalement, on n'appelle pas deux fois setContentView, mais si vous le faîte, seul le dernier va définir la vue en écrasant le précédent.
Pour ce faire il faudra créer un fichier XML dans les ressources. L'utilisation de XML facilite grandement le design du layout. Il permet de styliser la vue un peu comme en CSS dans les pages HTML (Le HTML est du XML). Dans l'IDE Android Studio on a aussi la possibilité d'utiliser un outil graphique : le Layout Editor . Il va nous permettre de créer le layout et voir le résultat dans l'Activity sans lancée l'application (jusqu'à certaines limites).
Pour ouvrir le Layout Editor, il suffit de cliquer sur un fichier XML de layout dans les ressources (res/layout). Il existe trois modes de vue :

Voici un exemple de XML "activity_main.xml" qui va créer un LinearLayout comme containeur principal avec un TextView comme enfant
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
Il faudra aussi avoir dans le code java l'instruction setContentView pour définir la vue.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
On expliquera plus tard le R.layout.activity_main, mais pour faire rapide, c'est le moyen d'accéder aux Ressources depuis le code Java. On verra qu'il existe la même chose quand on est dans le XML.
Il faudra créer des instances des différents éléments de la vue que vous voulez voir apparaître. Inconvénient il faudra parfois aller chercher la méthode qui correspond à l'attribut XML pour modifier le composant.
Dans l'exemple xml précédent pour définir la taille du composant, on utilise l'attribut layout_width et layout_height. Si on voulait faire la meme chose juste programmatiquement on ferait.
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
Ici on voit qu'on doit passer par un objet LayoutParams pour donner la largeur et la hauteur du composant.
Si l'on veut exactement la même chose que dans le fichier XML précédent, on devra avoir le code :
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
Au final, c'est rarement le XML ou le Java que l'on va utiliser pour créer nos Layout. Mais plus une combinaison des deux.
Quand on voudra ajouter des événements ou modifier la vue pendant l'exécution, on n'aura pas le choix de le faire en Java.
Imaginons un mock up comme celui la

Si les vignettes rouges (une image et un texte) proviennent d'une base de donnée, on ne pourra pas savoir combien il y en aura en tout. On n'aura pas le choix de mettre la main sur la boite grise et d'ajouter programmatiquement les vignettes dans la vue. Par contre, on utilisera le XML pour styliser la vue.
Souvent on va vouloir "mettre la main" sur une vue créée en XML, pour être capable d'interagir avec elle à travers le code Java. Comme dans l'exemple précédent où on voulait remplir la boite grise de Vignette.
Dans la classe view il existe un attribut id. C'est grâce à cet id que l'on va être capable de "mettre la main" sur une vue particulière dans une activity.
Il existe une methode findViewById(int id), cette méthode devrait vous rappeler une méthode utiliser en JavaScript pour mettre la main sur un élément du DOM (document.getElementById()).
Reprenons l'exemple précédent avec le TexView.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
La ligne android:id="@+id/text_view" permet d'ajouter un attribut id sur le TextView, la valeur de l'id sera text_view . On expliquera plus tard le @ et le +. Voilà le code pour accéder au TexteView depuis le Java.
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
Dans le SDK Android il y a déjà des View et ViewGroup codés pour nous. Voyons une liste des principaux utilisés dans ce cours.
Permet d'avoir des enfants à l'intérieur. En fonction des conteneurs les enfants auront un layout différent
L'un des plus simples à utiliser. Il permet d'avoir des enfants les uns en dessous des autres (VERTICAL) ou les uns a côté des autres (HORIZONTAL).
Ce ViewGroupe affiche les enfants dans des positions relatives. La position de chaque enfant peut être spécifiée par rapport aux éléments enfants ou par rapport à la zone parent
Permet d'ajouter un défilement si le contenu dépasse de la vue. Existe aussi le HorizontalScrollView
ConstraintLayout vous permet de créer des mises en page volumineuses et complexes. Il est similaire au RelativeLayout en ce sens que toutes les vues ont disposées en fonction des relations entre les vues, mais il est plus flexible que le RelativeLayout. Ce composant ne sera pas traité en cours.
Ce sont les composants d'affichage, comme un bouton un label ou une image.
Voici une liste des principaux :
Il existe beaucoup d'autre composant, mais on ne peut pas tous les détailler ici.
Chaque View et ViewGroup ont leurs propres attributs XML. Certains attributs sont spécifiques à un objet View, mais ces attributs sont hérités du View parent. Comme tous les composants et containeurs héritent de View ils ont plusieurs attributs en commun. Voici les quelques attributs importants. Pour la majorité ils viennent de View.
Tout objet View peut avoir un ID entier qui lui est associé, pour identifier de manière unique la vue. Lorsque l'application est compilée, cet ID est référencé sous forme d'entier, mais l'ID est généralement attribué dans le fichier XML de mise en page sous forme de chaîne, dans l'attribut id. Il s'agit d'un attribut XML commun à tous les objets View. Voici la syntaxe de creation d'un id par XML.
android:id="@+id/my_id"
ici le "@" veut dire qu'on va accéder aux ressources, le "+id" est là pour demander de créer un id ou d'utiliser celui existant.
Comme on l'a vu précédemment on va pouvoir accéder au View depuis son id grâce à findViewById(id_view).
Tous les attributs jouant sur le layout de la vue vont commencer par layout_quelquechose. Par exemple pour définir le la largeur et la hauteur, on devra utiliser layout_width et layout_height . On peut définir une taille exacte, mais la plupart du temps, on va préférer utiliser une de ses deux valeurs.
Gravity est l'attribut à appliquer sur les enfants. Permet d'expliquer la position dans l'espace que l'enfant prend. Layout_gravity permet de définir la position par rapport au parent.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>

Voici le résultat dans l'émulateur.

Voici l'explication
Voici un attribut spécifique au LinearLayout qui va être très utile pour faire des designs Responsive. Il va nous permettre d'expliquer le poids que l'objet va prendre dans la vue
Le LinearLayout va additionner tous les poids et faire en sorte que la vue la fraction désirée du poids total.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
Ici comme le LinearLayout est vertical il va additionner tous les poids soit 60+40 = 100 et faire en sorte que le premier bouton fasse 40/100 et le deuxième 60/100

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Dans le cas ou le LinearLayout est horizontal le poids sera sur le width

Intent est un objet messager pouvant réaliser une action sur les composants principaux. Il permet de faciliter la communication. Il existe trois cas d'utilisation :
il existe 2 types d'Intent:
Dans le cadre de ce cours, on va se concentrer sur les intents explicites. On peut lister 3 cas d'utilisation lorsque l'on démarre une activité :
Le plus simple, on va juste donner le nom de l'activité que l'on veut démarrer.
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
startActivity() va demander au système de créer une nouvelle Activité et l'ajouter en haut de la pile des activités. C'est donc celle-ci qui va devenir visible.

L'objet Intent est un messager, il peut donc aussi contenir un message. On va utiliser l'objet extra pour sauvegarder de l'information. Celui-ci se comporte comme un HashMap avec une clef et une valeur.
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Une fois dans SecondeActivity il faudra en premier lieu mettre la main sur l'Intent qui a démarré l'activité. Pour cela, on utilise getIntent().
Reste à récupérer les valeurs avec les mêmes clefs.
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
dans le cas de getIntExtra on nous demande la valeur par défaut s'il ne trouve pas la clef.
On peut schématiser par

Dance ce cas, on va devoir démarrer l'activité en expliquant qu'on attend un résultat en retour.
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
ActivityResultLauncher est comme un événement qu'on utiliserait. C'est la méthode onActivityResult qui sera appelée quand on reviendra sur l'activité. La méthode result.getData() nous permettra de mettre la main sur l'Intent avec les données qui proviennent de l'autre activité, ici SecondeActivity.
Voyons le code dans la deuxième activité pour ajouter de l'information.
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
Ici on exécute du code quand on clique sur un bouton :
Référence vers la DOC
Les menus sont un composant d'interface utilisateur courant dans de nombreux types d'applications.
Depuis Android 3.0 (API 11), les appareils ne sont plus tenus de fournir un bouton physique pour le menu. Pour palier è ce problème, on hérite de AppCompatActivity qui va gérer l'absence ou la présence du menu.
Il existe trois types de menu
Dans le cadre du cours, on détaillera que le premier type de menu. Les autres s'utilisent de façon similaire
Comme pour les vues, on peut utiliser le xml pour définir un menu. Le fichier se retrouvera dans le répertoire res/menu .
Android Studio a ajouté un Menu Éditeur graphique pour la création des menus.
Pour créer un nouveau menu XML vous devez faire :

il existe 3 tags pour définir les menus

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
Après définition du menu en XML, il va falloir l'associer à l'activité ou on veut qu'il s'affiche
Pour cela on va redéfinir la méthode onCreateOptionMenu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
Comme pour le XML des views on a un dé-sérialiseur, ici le MenuInflater
Pour ajouter programmatiquement un item on doit utiliser la méthode add() de l'objet Menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
Lorsque l'utilisateur sélectionne un élément dans le menu des options (ou l'action bar), le système appelle la méthode onOptionsItemSelected() de votre activité. Cette méthode transmet le MenuItem sélectionné.
On pourra identifier l'item sélectionné grâce à getItemId
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
Référence vers la DOC
Une boîte de dialogue est une petite fenêtre qui affiche à l'utilisateur de l'information, ou lui permet de prendre une décision ou à saisir des informations supplémentaires.
Les boîtes de dialogue sont dites modales:
La classe de base pour faire un dialog est Dialog mais on ne va pas utiliser celle-ci directement. Il faudrait tout redéfinir ce qui serait beaucoup de travail à chaque fois. On va plutôt utiliser une des classes enfant déjà écrite pour nous :
Pour créer des AlertDialog il faut utiliser le modèle Builder (Builder pattern).
Ce modèle permet de construire des objets complexes simplement.

Utilise les méthodes sur le builder
méthode create va créer une instance de l'AlertDialog
permet de créer rapidement un objet en évitant toute la complexité
La classe AlertDialog vous permet de créer une variété de design différent.
Ce sera souvent la seule dont vous aurez besoin.

1 - Titre : permet d'afficher un titre en haut, optionnel
2 - Zone de contenue : très flexible, elle permet d'afficher un message, des listes ou une vue personnalisée.
3 - Les boutons d'action : au nombre de trois maximums, optionnel
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
On peut aussi utiliser des strings qui proviendraient des ressources comme R.string.title_ad
Permet de demander une action à l'utilisateur et définir l'action à faire.
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
On peut ajouter 3 types de liste :
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
Pour ajouter la liste d'éléments, on pourrait aussi utiliser les ressources avec un string-array
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
on aurait alors dans le code
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
On utilisera la méthode setSingleChoiceItems(int itemsId, int checkedItem,final OnClickListener listener)
On utilisera la méthode setMultiChoiceItems(int itemsId, boolean[] checkedItems, final OnMultiChoiceClickListener listener)
Il faut en premier créer une vue, soit programmatiquement, soit en utilisant un fichier xml. Ensuite, il faut utiliser la méthode setView(View) sur le Builder pour définir la vue.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
On peut utiliser la méthode findViewById sur view pour mettre la main sur les éléments de la vue de l'alertdialog.
EditText edLogin = view.findViewById(R.id.ed_login_ad);
On pourrait très bien ajouter un bouton dans la vue et redéfinir l'événement dessus, on pourrait aussi ajouter les boutons prédéfinis du builder.
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
Lors de la redéfinissions de l'événement, on peut mettre la main sur l'alertdialog en castant (DownCast) le DialogInterface. On peut alors aller récupérer n'importe quel élément de la vue avec findViewById .
Il existe plusieurs façons d'intercepter les événements provenant de l'utilisateur. L'approche consiste à capturer les événements à partir de l'objet View spécifique avec lequel l'utilisateur interagit. La classe View fournit plusieurs moyens de le faire.
On peut catégoriser ces événements en 2 types :
Comme déjà utilisé dans d'autres cours. C'est une simple méthode de retour (CallBack) que l'on redéfinie.
Sur toutes les interfaces qui héritent de View on aura ces événements.
Ceci est appelé lorsque l'utilisateur touche l'élément.
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
On a la View sur laquelle on a cliqué en paramètre de onClick
Déclenché quand l'utilisateur reste appuyé sur une view
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
onLongClick renvoie un boolean, il permet de savoir si l'événement a été consommé ou non.
Déclenché lorsque l'utilisateur navigue vers, ou hors de l'élément, en utilisant les touches de navigation
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
Va fonctionner davantage pour les views qui requièrent une interaction (ex : EditText)
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
Permet de contrôler les actions sur un EditText
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
Cela renvoie un booléen pour indiquer si vous avez consommé l'événement et qu'il ne doit pas être porté plus loin. Autrement dit, renvoyez true pour indiquer que vous avez géré l'événement et qu'il devrait s'arrêter ici ; renvoie false si vous ne l'avez pas géré et/ou si l'événement doit continuer pour tous les autres écouteurs au clic.
C'est un événement particulier des appareils tactiles. Quand l'utilisateur place 1 ou plusieurs doigts sur l'écran ça déclenche la méthode de rappel onTouchEvent.
L'événement va prendre en compte :
C'est à travers l'objet MotionEvent que l'on pourra récupérer toutes ses informations
Grâce a la Méthode getActionMasked on est capable de récupérer l'état du touch de l'écran. Savoir si le doigt est posé, bouge ou est soulevé
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
Dans le cas où on a 1 doigt, getX et getY nous renvoie la position du doigt sur l'écran.
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
Dans le cas où il y a plusieurs doigts le système génèrent ces touchEvent
la méthode getX ou getY peut prendre en paramètre l'index du pointeur dont on veut la position
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
Pour aider sur les manipulations de l'onTouch, il y a dans le SDK une interface pour détecter certain type de mouvement. C'est le GestureDetector
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
Permet d'enregistrer des informations de petites taille dans une collection sous format clef/valeur:
Ces informations sont accessibles par n'importe quelle activité de l'application
Les données persistent malgré un redémarrage ou une mise à jour de l'application
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
remarque: on utilise MODE_PRIVATE, mais il n'existe plus d'autre mode que celui-ci. Avant on avait MODE_WORLD_WRITEABLE ou MODE_WORLD_READABLE, mais c'est déprécié et si on essaie d'accéder au SharedPreferences depuis une autre application, cela déclenche une exception de sécurité
Depuis l'objet SharedPreferences utiliser les méthodes sharedPreferences.getXXX("key", defautValue) ou XX correspond à un type primitif et "key" la clef utilisée pour sauvegarder la donnée.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
Pour ajouter des données de type primitif il faut passer par l'objet SharedPreferences.Editor
Une fois ajouté il faut utiliser commit ou apply pour synchroniser les infos sur le disque.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
apply() modifie immédiatement l'objet SharedPreferences en mémoire, mais écrit les mises à jour sur le disque de manière asynchrone. Vous pouvez également utiliser commit() pour écrire les données sur le disque de façon synchrone. Cependant, comme commit() est synchrone, évitez de l'appeler à partir de votre thread principal, car cela pourrait suspendre le rendu de l'interface utilisateur.
On peut soit supprimer toutes les données, soit seulement une donnée par clef.
Doit aussi appeler apply ou commit pour synchroniser les modifications
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
Même procédé que vue dans le cours de Java I pour manipuler les streams, seul nuance il existe une memoir interne ou une memoire externe
Le mode d'accès est forcément privée
context.getFilesDir(): Renvoie le chemin absolu du répertoire sur le système de fichiers où les fichiers créés avec openFileOutput(String, int) sont stockés.
Aucune autorisation supplémentaire n'est requise pour que l'application appelante puisse lire ou écrire des fichiers sous le chemin renvoyé.
File file = new File(context.getFilesDir(), filename);
Ecrire dans un fichier
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
Lire dans un fichier
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
Premièrement on doit déclarer une permission dans le manifest
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
Pour tester Débrancher le cable, car sinon la mémoire externe sera "monter" sur le pc
Aucune certitude que les données soient présentes, car elles sont publiques et modifiables par toutes les autres applications.
Les repertoires pour stocker des informations suivent un standard pour toutes ses photos, ses musiques et fichiers audio.
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
Sinon même chose que memoire interne pour manipulation des fichiers.
BD locale, accessible que par l'application (privée) et même que par le téléphone
Le système de gestion de base de donnée est SQLite .
Android conseil d'utiliser leur framework Room pour accéder aux bases de données. Dans ce cours, on va utiliser l'API SQLite que Room utilise.
Dans SQLite il existe que 5 types
On peut aussi ajouter des contraintes
ex: création d'une table d'étudiant
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
Pour mettre la main sur la BD on doit passer par une classe qui hérite de SqliteOpenHelper
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Lorsqu on crée une instance de cette classe, on peut ensuite mettre la main sur la BD avec getWritableDatabase ou get ReadableDatabase().
Détaillons le constructeur :
onCreate : appelé la premiere fois que l'on essaie d'accéder à la BD ou quand la version = 1
onUpgrade : si on change le numéro de la version cette méthode est alors appelée. On est libre de changer la structure des tables ou tous autres actions SQL
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
Pour gérer les versions et mettre plus facilement la main sur la base de donnée on pourrait créer une classe ConnectionDB
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
On va utiliser la base de donnée comme en JavaII avec un Manager pour chaque table.
Ici on va faire un EtudiantManager
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
On utilise un objet ContentValues clef/valeur pour ajouter les données. Les clefs doivent être les mêmes que les colonnes de la table.
la methode insert retourne l'id autogénéré.
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
détaillons les paramètres de la méthode delete
public int delete (String table,
String whereClause,
String[] whereArgs)
Si on avait écrit la requête SQL pour supprimer un étudiant, on aurait écrit :
DELETE FROM etudiant WHERE id = ?
WHERE id = ? : est la condition de suppression ou le whereClause on appelle le ? un joker. Il sera remplacer par la valeur voulue.
Si on avait voulu supprimer l'étudiant avec l'id = 7 on aurait eu :
DELETE FROM etudiant WHERE id = 7
7 est le whereArgs ou l'argument du where, soit la condition changeante.
On aurait pu avoir
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
Ici on a 2 conditions dans le where clause. C'est pour cela que le whereArgs est un tableau de String. La premiere valeur va correspondre au premier ? et la deuxième valeur au deuxième ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
On va réutiliser le même principe que le whereClaus et le whereArgs.
Seul les valeurs ajoutées dans le ContentValues seront modifiées.
comme précédemment on doit avoir les mêmes clefs que les noms des colones
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
L'objet Cursor est quasiment le même que l'objet ResultSet du cours de JavaII. C'est une structure de donnée de type Set. On va la parcourir avec la boucle while.
Après l'appelle de moveToNext() on a un nouvel enregistrement de la table. S'il n'y a plus d'enregistrement, moveToNext() renverra false
Dans le cas d'une requête avec des paramètres, on va devoir utiliser le whereArgs.
Exemple pour récupérer les étudiants ayant un âge supérieur à :
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
La plupart des appareils fonctionnant sous Android ont des capteurs intégrés qui mesurent le mouvement, l'orientation et diverses conditions environnementales. Une application météorologique peut utiliser le capteur de température et le capteur d'humidité d'un appareil pour calculer et signaler le point de rosée. Un jeu pourrait utiliser l'accéléromètre pour déplacer une image avec le mouvement du téléphone.
il existe 3 catégories de Sensor dans les appareils :
DOC Les capteurs de gravité, d'accélération linéaire, de vecteur de rotation, de mouvement significatif, de compteur de pas et de détecteur de pas sont soit matériels, soit logiciels. Les capteurs de l'accéléromètre et du gyroscope sont toujours basés sur le matériel (hardware).
DOC La plate-forme Android propose deux capteurs permettant de déterminer la position d'un appareil : le capteur de champ géomagnétique et l'accéléromètre.
DOC La plate-forme Android fournit quatre capteurs qui vous permettent de surveiller diverses propriétés environnementales. Vous pouvez utiliser ces capteurs pour surveiller l'humidité ambiante relative, l'éclairement, la pression ambiante et la température ambiante à proximité d'un appareil Android.
Les quatre capteurs d'environnement sont basés sur le matériel et ne sont disponibles que si le fabricant de l'appareil les a intégrés à un appareil.
Pour récupérer les données des sensors, ce sera toujours de la même façon à travers le Framework Sensor.
On utilisera 4 classes/interfaces
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Depuis SensorManager on peut lister les sensors présent dans le téléphone.
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
La première chose s'est de vérifier si le sensor que l'on veut utiliser existe. Pour cela on va essayer de le récupérer depuis le sensorManager. On fait généralement cela dans onCreate.
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
Pour connaitre la constante Sensor.TYPE_LIGHT qui correspond au sensor que l'on veut, il faut aller voir dans la DOC .

Méthodes utiles :
Pour lire les données provenant des Sensor il faut implementer deux méthodes de l'interface SensorEventListener. Elles sont appelées par le système.
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
On aurait aussi pu utiliser implement dans l'activité ou la class qui nous arrange
Pour enregistrer le listener on le fait dans onResume sur l'objet sensorManager et va préciser le délai d'écoute du sensor.
On fait ça dans onResume, car si on quitte l'activité et qu'on revient dessus onResume est appelé dans tous les cas.
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
Lorsque l'on quitte l'activité et qu'elle passe en pause, il faut arrêter d'écouter le sensor. Écouter les sensors est une étape qui consomme beaucoup de batterie. Donc, il est important quand on quitte l'activité d'arrêter d'écouter le sensor.
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
Tout va se passer dans onSensorChanged(SensorEvent event), les données vont être ajoutées dans l'objet SensorEvent. Plus précisément dans event.values .
values est un tableau de float qui va contenir la ou les valeurs du sensor.
Il faut maintenant savoir combien de donnée on a pour le sensor. Ici encore c'est la DOC qui va nous donner l'information.

Dans notre cas il n'y a qu'une seule valeur, mais si on regarde le magnétomètre, c'est différent.

Si on veut afficher la valeur du luxmètre (mesure de la lumière) en lux (unité de mesure de la lumière) dans un TextView, voici le code
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
L'avantage ici, c'est qu'il y a qu'une façon d'accéder à tous les sensors. Seul le nombre de valeurs dans le tableau event.values va changer.
Si vous publiez votre application sur Google Play, vous pouvez utiliser l'élément <uses-feature> dans votre fichier manifeste pour filtrer votre application des appareils qui n'ont pas la configuration de capteur appropriée pour votre application.
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.appname'
compileSdk 32
defaultConfig {
applicationId "com.example.appname"
minSdk 25
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_app";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate:");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
public class FirstActivity extends Activity {
}
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<application
... >
<activity android:name=".FirstActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivité"
android:exported="false"/>
</application>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this; //don t forget this line, else you will have NullPointer
setContentView(R.layout.activity_main);
}
}
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//set UI width XML File
setContentView(R.layout.activity_main); //we give here reference of XML file
//set view width Java File
LinearLayout container = new LinearLayout(context);
setContentView(container);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
TextView tv = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//create instance of linear layout
LinearLayout linearLayoutMain = new LinearLayout(context);
linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
linearLayoutMain.setOrientation(LinearLayout.VERTICAL);
//add linearLayout as main container of activity
setContentView(linearLayoutMain);
//create textview
TextView textView = new TextView(context);
textView.setText("Hello World!");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//set text view as child of linearlayout
linearLayoutMain.addView(textView);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
//access to textview ass by xml
TextView textView = findViewById(R.id.text_view);
//change value of textview
textView.setText("New text to print");
}
}
android:id="@+id/my_id"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Hello World!" />
<TextView
android:layout_width="match_parent"
android:gravity="right"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40"
android:text="btn 1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
android:text="btn 2" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="btn 1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="btn 2" />
</LinearLayout>
Intent intent = new Intent(ctx,ClassName.class);
startActivity(intent);
Intent intent = new Intent(this, SecondeActivity.class);
intent.putExtra("name","user name");
intent.putExtra("id", "456-fesdf-464sdf");
intent.putExtra("year", 27);
startActivity(intent);
Intent intent = getIntent();
String nameValue = intent.getStringExtra("name");
String idValue = intent.getStringExtra("id");
int yearValue = intent.getIntExtra("year", -1);
ActivityResultLauncher<Intent> resultActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
//do instruction when result
Intent intent = result.getData();
String dataString = intent.getStringExtra("dataKey");
}
}
}
);
Intent intent = new Intent(this, SecondeActivity.class);
resultActivity.launch(intent);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("dataKey","hello data"); //1
setResult(RESULT_OK, intent); //2
finish(); //3
}
});
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_play"
android:icon="@android:drawable/ic_media_play"
android:title="play"
app:showAsAction="always" />
<item
android:id="@+id/menu_stop"
android:icon="@android:drawable/ic_media_stop"
android:title="stop"
app:showAsAction="always" />
<item
android:id="@+id/menu_next"
android:title="next"
app:showAsAction="always" />
<item
android:id="@+id/menu_pause"
android:icon="@android:drawable/ic_media_pause"
android:title="pause"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menu_reset"
android:title="reset"
app:showAsAction="never" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.layout_menu, menu);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int idItem = 1; // exemple pour ajouter un item
int order = 1;
MenuItem menuItem = menu.add(0, idItem, order, "mon menu");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean retour = super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.menu_play:
//action todo
retour = true;
break;
case R.id.menu_stop:
//action todo
retour = true;
break;
case R.id.menu_pause:
//action todo
retour = true;
break;
case R.id.menu_next:
//action todo
retour = true;
break;
case R.id.menu_reset:
//action todo
retour = true;
break;
}
return retour;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
AlertDialog dialog = builder.create();
dialog.show();
//or
AlertDialog dialog = builder.show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setMessage("my beautiful Message to print ");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if yes is select
}
});
builder.setNeutralButton("i don't know", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if i don't know is select
}
});
builder.setPositiveButton("no", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//action if no select
}
});
AlertDialog dialog = builder.show();
String[] items = new String[]{"orange","blue","green"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = items[which];//which = position of item select
}
});
AlertDialog dialog = builder.show();
<string-array name="colors_list">
<item>orange</item>
<item>blue</item>
<item>green</item>
</string-array>
builder.setItems(R.array.colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] items = getResources().getStringArray(R.array.colors_list); //pour récupérer les données depuis le répertoire Ressource
String value = items[which];//which = position of item select
}
});
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="login : " />
<EditText
android:id="@+id/ed_login_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="password : " />
<EditText
android:id="@+id/ed_password_ad"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="70" />
</LinearLayout>
</LinearLayout>
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("my wonderful title");
View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_layout,null);
builder.setView(view);
AlertDialog dialog = builder.show();
EditText edLogin = view.findViewById(R.id.ed_login_ad);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog alertDialog = (AlertDialog) dialog;
EditText edLogin = alertDialog.findViewById(R.id.ed_login_ad);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//action to do
v.setBackgroundColor(Color.GREEN);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
v.setBackgroundColor(Color.GREEN);
}else{
v.setBackgroundColor(Color.BLUE);
}
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
public class MainActivity extends AppCompactActivity {
...
// exemple pour une activité, mais même approche pour une sous classe de View
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
//exemple sur une sous-classe de View
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
//action to do
return true;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
float xPosition = 0;
float yPosition = 0;
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
xPosition = event.getX();
yPosition = event.getY();
}
if(event.getActionMasked() == MotionEvent.ACTION_MOVE){
xPosition = event.getX();
yPosition = event.getY();
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID from pointerIndex
int pointerId = event.getPointerId(pointerIndex);
// get action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "index down: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_DOWN: {
Log.d(TAG, "index down: " + pointerId);
break;
}
case MotionEvent.ACTION_MOVE: { // a pointer was moved
Log.d(TAG, "index move: " + pointerId);
break;
}
case MotionEvent.ACTION_UP:
Log.d(TAG, "index up: " + pointerId);
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d(TAG, "index up: " + pointerId);
break;
}
return true;
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
public class EventActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
private String TAG = "debug-app";
GestureDetector gestureDetector;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_event);
gestureDetector = new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
//si pas besoin de catégoriser les informations
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//si besoin de catégoriser
SharedPreferences sharedPreferencesUser = context.getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String guid = sharedPreferences.getString("id",null);
int age = sharedPreferences.getInt("age",-1);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "John Doe");
editor.putFloat("xPosition", 42.56f);
editor.putFloat("yPosition", 1056.89f);
editor.apply();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
//suppression par clef
editor.remove("userName");
editor.remove("id");
editor.apply();
//suppression total
editor.clear();
editor.apply();
File file = new File(context.getFilesDir(), filename);
String filename = "myFile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.toByteArray());
}
FileInputStream fileInputStream = context.openFileInput(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred when opening raw file for reading.
} finally {
String contents = stringBuilder.toString();
}
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
File file = new File(Environment.getExternalStorageDirectory().getPath()+ File.separator+ "Android/data"+File.separator + getPackageName() + "/files/"+"myFile.txt" );
CREATE TABLE etudiant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT,
age
);
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE etudiant (\n" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"first_name TEXT," +
"last_name TEXT," +
"age" +
");");
db.execSQL("INSERT INTO etudiant ('first_name','last_name','age') values ('john','doe', 27), ('foo','bar',99);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS etudiant");
onCreate(db);
}
public class ConnectionDB {
private static int version = 1;
private static String bnName = "myBd.db";
private static SQLiteDatabase bd = null;
private static DataBaseHelper helper;
public static SQLiteDatabase getBd(Context context){
if(helper == null){
helper = new DataBaseHelper(context, bnName, null, version);
}
bd = helper.getWritableDatabase();
return bd;
}
public static void close(){
if(bd!= null && !bd.isOpen()){
bd.close();
}
}
}
public class EtudiantManager {
public static long add(Context context, Etudiant etudiantToAdd){
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToAdd.getFirstName());
contentValues.put("last_name", etudiantToAdd.getLastName());
contentValues.put("age", etudiantToAdd.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context); //on réutilise ConnctionDB ici
return bd.insert("etudiant", null, contentValues);
}
}
public static void delete(Context context, int idEtudiant){
SQLiteDatabase bd = ConnectionDB.getBd(context);
bd.delete("etudiant","id = ?" , new String[]{String.valueOf(idEtudiant)});
}
public int delete (String table,
String whereClause,
String[] whereArgs)
DELETE FROM etudiant WHERE id = ?
DELETE FROM etudiant WHERE id = 7
DELETE FROM etudiant WHERE id = ? AND name LIKE ?
public static void update(Context context, Etudiant etudiantToUpdate) {
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", etudiantToUpdate.getFirstName());
contentValues.put("age", etudiantToUpdate.getAge());
SQLiteDatabase bd = ConnectionDB.getBd(context);
long nbRowChange = bd.update("etudiant", contentValues, "id = ?", new String[]{String.valueOf(etudiantToUpdate.getId())});
}
public static ArrayList<Etudiant> getAll(Context context) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, null);
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
public static ArrayList<Etudiant> getByAgeLimite(Context context, int ageLimite) {
SQLiteDatabase bd = ConnectionDB.getBd(context);
String query = "SELECT * FROM etudiant where age > ?";
ArrayList<Etudiant> etudiants = null;
Cursor cursor = bd.rawQuery(query, new String[]{String.valueOf(ageLimite)});
if (cursor.isBeforeFirst()) {
etudiants = new ArrayList<>();
while (cursor.moveToNext()) {
Etudiant etudiant = new Etudiant();
etudiant.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
etudiant.setFirstName(cursor.getString(cursor.getColumnIndexOrThrow("first_name")));
etudiant.setLastName(cursor.getString(cursor.getColumnIndexOrThrow("last_name")));
etudiant.setAge(cursor.getInt(cursor.getColumnIndexOrThrow("age")));
etudiants.add(etudiant);
}
}
return etudiants;
}
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("debug_app", "sensor: " + sensor.getName());
Log.d("debug_app", "sensor: " + sensor.getMinDelay());
Log.d("debug_app", "sensor: " + sensor.getVersion());
Log.d("debug_app", "sensor: " + sensor.getMaximumRange());
}
Sensor sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(sensorLight != null){
// sensor existe
} else {
// prévenir l'utilisateur qu'on ne peut pas continuer
}
SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
public class SensorActivity extends AppCompatActivity {
TextView textView;
SensorManager sensorManager;
SensorEventListener sensorEventListener;
Sensor sensorLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
textView = findViewById(R.id.text);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float luxValue = event.values[0];
textView.setText(String.valueOf(luxValue) + " lux");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorLight, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener,sensorLight);
}
}
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />